<template>
  <div class="border border-gray-300 rounded">
    <Toolbar
      class="border-b border-gray-300 rounded-tl-lg rounded-tr-lg"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="overflow-y: hidden"
      :style="{ height: props.height + 'px' }"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const props = defineProps({
  height: { type: Number, default: 400 },
  value: { type: String, default: '' },
})
const mode = ref('default') // default | simple
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 编辑器内容 HTML
const valueHtml = ref('')
const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

const emits = defineEmits(['update:value'])

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = editor => {
  editorRef.value = editor // 记录 editor 实例，重要！
  // 回显数据内容
  props.value && editorRef.value.setHtml(props.value)
}

const handleChange = editor => {
  // 更新表单content数据
  emits('update:value', editor.getHtml())
}
</script>

<style lang="scss" scoped></style>
